package com.TCP_UDP网络编程.UDP_网络编程;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

@SuppressWarnings("all")
public class UDP01_Receiver接收端 {
    public static void main(String[] args) throws IOException {

        /// 1.等待连接，接受数据
        DatagramSocket socket = new DatagramSocket(9999);  ///接受端的配置；让该程序在本机的9999端口监听；
        byte[] bytes = new byte[1024];                          ///用来接受发送端的内容的数组；
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
        System.out.println("接受等待中~~");
        socket.receive(packet);                             ///等待连接中；连接好后内容装到packet中

        /// 2.将接收到的数据拆包处理
        int length = packet.getLength();               ///拆包，
        byte[] data = packet.getData();               ///拆包
        String s = new String(data, 0, length);///拼成字符串
        System.out.println(s);                      ///输出


        /// 3.回复
        byte[] bytes1 = "接受成功~~".getBytes();
        DatagramPacket packet1 =            ///装包，指定主机和端口
                new DatagramPacket(bytes1, bytes1.length, InetAddress.getLocalHost(), 9998);
        socket.send(packet1);               ///发送

        /// 4.关闭资源
        socket.close();                     ///关闭
    }
}
